package cn.dong.sms.service.impl;

import cn.dong.sms.service.SmsService;
import cn.dong.base.handler.CustomException;
import cn.dong.sms.utils.FormUtils;
import cn.dong.sms.utils.RandomUtils;
import cn.dong.sms.utils.SmsProperties;
import com.aliyuncs.exceptions.ClientException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class SmsServiceImpl implements SmsService {


    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private SmsProperties smsProperties;

    /**
     * 发送短信
     *
     * @param phone
     */
    @Override
    public String send(String phone) throws ClientException {
        // 校验手机号码
        if (!FormUtils.isMobile(phone) || phone == null) {
            throw new CustomException(40000, "手机号格式不正确！");
        }
        // 生成四位随机数
        String ranCode = RandomUtils.getFourBitRandom();
//        // 发送短信
//        DefaultProfile profile = DefaultProfile.getProfile(smsProperties.getRegionId()
//                , smsProperties.getAccessId(), smsProperties.getAccessSecret());
//        IAcsClient client = new DefaultAcsClient(profile);
//
//        CommonRequest request = new CommonRequest();
//        request.setSysMethod(MethodType.POST);
//        request.setSysDomain("dysmsapi.aliyuncs.com");
//        request.setSysVersion("2017-05-25");
//        request.setSysAction("SendSms");
//        request.putQueryParameter("RegionId", smsProperties.getRegionId());
//        request.putQueryParameter("PhoneNumbers", phone);
//        request.putQueryParameter("SignName", smsProperties.getSignature());
//        request.putQueryParameter("TemplateCode", smsProperties.getTemplate());
//        Map<String, String> mapPhone = new HashMap<String, String>(1);
//        mapPhone.put("code", ranCode);
//        // 转json
//        String json = JSON.toJSONString(mapPhone);
//        request.putQueryParameter("TemplateParam", json);
//        CommonResponse response = client.getCommonResponse(request);
//        // 判断结果，讲返回数据转Java对象
//        String data = response.getData();
//        Map<String, String> parse = (Map<String, String>) JSON.parse(data);
//        // 获取信息和状态码
//        String message = parse.get("Message");
//        String code = parse.get("Code");
//        if (!"OK".equals(code) || !"OK".equals(message) ) {
//            throw new CustomException(40000, "发送验证码失败，请稍后重试！");
//        }

        // 保存到redis
        redisTemplate.opsForValue().set(phone, ranCode, 5, TimeUnit.MINUTES);
        // 返回
        return ranCode;
    }
}
